<template>
  <div class="cart">
    <div id="container"></div>
    <!--    安全图标-->
    <div class="HomeIndex">
      <van-image
          width="50px"
          height="50px"
          src="https://img95.699pic.com/element/40106/6770.png_860.png"
      />
    </div>
    <div class="cart-type">
      <div class="cart-type-price">
        <van-list>
          <van-cell v-for="(item,index) in cartTypeList" :key="index" :title="item.cartype" :value="item.cartype">

            <div class="icon">
              <van-icon name="records-o"/>
            </div>
            <div class="cart-name">{{ item.typeName }}</div>
          </van-cell>
        </van-list>
        <div class="priceCard">
          <div class="price"><span class="estimatedPrice">预估价{{ estimatedPrice }}元</span></div>
          <div class="price1"><span class="estimatedPrice1">预估价{{ estimatedPrice1 }}元</span></div>
          <div class="price2"><span class="estimatedPrice2">预估价{{ estimatedPrice2 }}元</span></div>
          <div class="price3"><span class="estimatedPrice3">预估价{{ estimatedPrice3 }}元</span></div>
        </div>
      </div>
    </div>
    <div>
      <van-radio name="1" v-model="radio" class="radio"></van-radio>
      <van-radio name="2" v-model="radio" class="radio2"></van-radio>
      <van-radio name="3" v-model="radio" class="radio3"></van-radio>
      <van-radio name="4" v-model="radio" class="radio4"></van-radio>
    </div>
    <div class="cart-time" @click="findByTime()">
      <van-icon name="clock-o" class="clock"/>
      <span class="clock-text">现在出发</span><br>
      <span>{{ orderTime }}</span>
    </div>
    <div class="cart-cart" @click="toHelpCartTwo()">
      <van-icon name="label-o" class="clock"/>
      <span class="clock-text">代叫车</span>
    </div>
    <div>
      <van-popup v-model="time" position="bottom" :style="{height: '50vh'}">
        <van-datetime-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="orderTime"
            type="datetime"
            title="选择完整时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirm"
        />
      </van-popup>
    </div>


    <van-button type="primary" style="width: 100%;margin-top: 0px;background-color: #4B9EFF" @click="findByOrder">叫车</van-button>

    <div class="popup">
      <van-popup v-model="popup" round position="bottom" :style="{ height: '60%' }">
        <div class="first">
          <div class="t">您有一笔订单尚未支付</div>
          <div class="order">
            订单编号：<span>{{ order1.orderId }}</span>
            <van-image src="https://tse2-mm.cn.bing.net/th/id/OIP-C.uxP3iOS9gvD97fWHc-OfQgHaHa?rs=1&pid=ImgDetMain"
                       width="22px" height="22px" @click="ctrlC($event)"/>
          </div>
          <div class="order">订单时间: {{ order1.orderTime }}</div>
          <div class="order">订单出发点: {{ order1.startingPointAddress }}</div>
          <div class="order">订单目的地: {{ order1.destinationAddress }}</div>
          <div class="icon">
            <van-image :src="order1.driverImgurl" width="120px" height="120px"/>
          </div>
          <div class="order" style="float:left; width: 280px;font-weight: bold">{{ order1.carNumber }}</div>
          <div class="order" style="float:left; width: 280px;font-size: 12px;color:#919A9F;">
            {{ order1.carColor }} | {{ order1.carName }}
          </div>
          <div class="order" style="float:left; width: 280px;font-size: 16px;color:#919A9F;">
            {{ order1.driverName }}
            <van-rate disabled v-model="this.order1.driverPoint"/>
            <span style="color: red;">{{ order1.driverPoint }}.0分</span>
          </div>
          <div class="money">¥ {{ order1.passengerTotal }}
            <span style="color:#40A6FF;font-size: 12px;margin-top: 24px;margin-left: 10px;">明细></span>
          </div>
          <div class="pay">
            <van-button round block type="info" @click="show1 = true"
                        style="background-color: #4EA9CB;width: 90%;position: absolute;bottom: 20px;">支付
            </van-button>
          </div>
        </div>
      </van-popup>
      <van-popup v-model="popup1" round position="bottom" :style="{ height: '70%' }">
        <div class="first">
          <div class="t">您有一笔违约金尚未支付</div>
          <div class="order">
            订单编号：<span>{{ order1.orderId }}</span>
            <van-image src="https://tse2-mm.cn.bing.net/th/id/OIP-C.uxP3iOS9gvD97fWHc-OfQgHaHa?rs=1&pid=ImgDetMain"
                       width="22px" height="22px" id="ctrl+c" @click="ctrlC($event)"/>
          </div>
          <div class="order">订单时间: {{ order1.orderTime }}</div>
          <div class="order">订单出发点: {{ order1.startingPointAddress }}</div>
          <div class="order">订单目的地: {{ order1.destinationAddress }}</div>
          <div class="order" style="font-size: 18px;font-weight: bold;margin-bottom: 30px;">原因: {{
              order1.closeCause
            }}
          </div>
          <div class="money">¥ 3.00
            <span style="color:#40A6FF;font-size: 12px;margin-top: 24px;margin-left: 10px;">明细></span>
          </div>
          <div class="pay">
            <van-button round block type="info" @click="show1 = true"
                        style="background-color: #4EA9CB;width: 50%;position: absolute;bottom: 20px;font-size: 16px">支付
            </van-button>
            <van-button round block
                        style="width: 30%;position: absolute;bottom: 20px;margin-left: 60%;border: 2px solid #D1D1D1;color:#4EA9CB;font-size: 16px">
              <van-icon style="font-size: 20px" name="phone"/>
              有疑问
            </van-button>
          </div>
        </div>
      </van-popup>
      <div>
        <van-popup v-model="show1" position="bottom" :style="{ height: '30%' }">
          <van-radio-group v-model="radio1">
            <van-cell-group>
              <van-cell title="微信支付" clickable @click="radio1 = '1'">
                <template #right-icon>
                  <van-radio name="1"/>
                </template>
              </van-cell>
              <van-cell title="支付宝支付" clickable @click="radio1 = '2'">
                <template #right-icon>
                  <van-radio name="2"/>
                </template>
              </van-cell>
              <van-button round block type="info" @click="toPay()">确定</van-button>
            </van-cell-group>
          </van-radio-group>
        </van-popup>
      </div>
      <div>
        <!--二维码组件，并给参数赋值-->
        <van-dialog v-model="show2" title="微信支付" show-cancel-button>
          <qr-code-component :text="data"/>
        </van-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
import QrCodeComponent from "@/views/purse/wx_pay/QrCodeComponent.vue";
import handleCopy from "@/utils/clipboard";
import {getOrder} from "@/api/purse/order";
import dayjs from "dayjs";

export default {
  components: {QrCodeComponent},
  data() {
    return {
      show2: false,
      data: '',
      show1: false,
      radio1: '',
      orderList: [],
      order1: {},
      popup: false,
      popup1: false,
      cartType: {
        typeName: "",
      },
      cartPrice: {
        orderInformation: {},
        orderTime: {},
        orderCost: {}
      },
      // cartTypePrice: null
      cartTypeList: [],
      //里程费
      mileageFee: null,
      //起步价
      startFee: null,
      //起步公里
      startingKilometer: null,
      //出发地
      startaddress: "",
      //出发地经纬度
      startLatitudeAndLongitude: this.$route.query.startLatitudeAndLongitude,
      //目的地
      endaddress: "",
      // 目的地经纬度
      endLatitudeAndLongitude: this.$route.query.endLatitudeAndLongitude,
      radio: '1',
      cartPriceList: [],
      estimatedPrice: null,
      estimatedPrice1: null,
      estimatedPrice2: null,
      estimatedPrice3: null,
      orderMileage: null,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      time: false,
      orderTime: null,
      driverTime: null,
      driverLong: null,
      order: {
        orderInformation: {
          //出发地经纬度
          startingPoint: "",
          // 目的地经纬度
          destination: "",
          //出发地
          startingPointAddress: "",
          //目的地
          destinationAddress: "",
          // 里程
          orderMileage: "",
        },
        orderTime: {
          orderTime: ""
        },
        orderCost: {}
      },
    }
  },
  created() {
    this.getOrder();
    if (this.startLatitudeAndLongitude) {
      this.initAMap()
    }
    this.startAndEnd()
    this.findByCartTypeList()
    this.findByMileageFee()
    this.makeTime()
  },
  mounted() {

  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    makeTime() {
      this.orderTime = this.$route.query.makeDate;
      this.startLatitudeAndLongitude = this.$route.query.startLatitudeAndLongitude;
      this.endLatitudeAndLongitude = this.$route.query.endLatitudeAndLongitude;
    },
    convertToFormat(dateTime) {
      return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss');
    },
    onConfirm(data) {
      this.orderTime = this.convertToFormat(data);
      this.time = false;
      console.log(this.orderTime);
    },
    findByTime() {
      this.time = !this.time;
    },
    toHelpCartTwo() {
      this.$router.push({
        path: '/helpCartTwo',
        query: {
          startaddress: this.startaddress,
          endaddress: this.endaddress,
          startLatitudeAndLongitude: this.startLatitudeAndLongitude,
          endLatitudeAndLongitude: this.endLatitudeAndLongitude
        }
      })
    },
    //监听订单状态
    monitorStatus(orderId, payWay) {
      //定时器,每3秒执行一次
      var interval = setInterval(() => {
        axios.post("http://localhost:8081/alipay/wx_pay/checkWx?orderId=" + orderId + "&payWay=" + payWay).then(res => {
          console.log("findStatus", res.data)
          if (res.data !== "NOTPAY" || this.show2 === false) {
            //关闭定时
            clearInterval(interval);
            if (res.data === "SUCCESS") {
              this.show2 = false;
              this.show1 = false;
              this.popup = false;
              this.popup1 = false;
              this.getOrder();
              this.startAndEndLongitude();
              this.startAndEnd();
              this.findByCartTypeList();
              this.findByMileageFee();
              this.$toast('支付成功');
            } else if (res.data === "CLOSED") {
              this.show2 = false;
              this.$toast('订单号重复,订单已取消');
            }
          }
        });
      }, 3000);
    },
    toPay() {
      if (this.radio1 === '1') {
        axios.post("http://localhost:8081/alipay/wx_pay/subWx?orderId=" + this.order1.orderId).then(res => {
          this.data = res.data;
          console.log(res.data);
          this.show2 = true;
          this.monitorStatus(this.order1.orderId, 1);
        })
      } else if (this.radio1 === '2') {
        window.open("http://localhost:8081/alipay/pay/payMoney?orderId=" + this.order1.orderId);
      } else {
        this.$toast('请选择支付方式')
      }
    },
    getOrder() {
      const userId = localStorage.getItem("userId");
      getOrder(userId).then((res) => {
        this.orderList = res.data;
      })
    },
    findByOrder() {
      let shouldRedirect = true;
      for (let i = 0; i < this.orderList.length; i++) {
        if (this.orderList[i].orderStatus === 6) {
          this.order1 = this.orderList[i];
          this.popup = true;
          shouldRedirect = false;
          break;
        } else if (this.orderList[i].orderStatus === 3) {
          this.order1 = this.orderList[i];
          this.popup1 = true;
          shouldRedirect = false;
          break;
        } else {
          // 如果需要，可以继续在这里添加处理逻辑
        }
      }
      if (shouldRedirect) {
        this.order.orderInformation.startingPoint = this.startLatitudeAndLongitude
        this.order.orderInformation.destination = this.endLatitudeAndLongitude
        this.order.orderInformation.startingPointAddress = this.startaddress
        this.order.orderInformation.destinationAddress = this.endaddress
        this.order.orderInformation.orderMileage = this.driverLong
        this.order.orderTime.orderTime=this.orderTime
        this.order.orderInformation.userId = localStorage.getItem("userId")
        axios.post('http://localhost:8081/passenger/order/addOrderInfo', this.order).then(response => {
          console.log(response)
          console.log("response.data.data", response.data.data)
          if (response.status === 200) {
            this.$toast.success('下单成功');
            this.$router.push({
              path: '/makeOrder',
              query: {
                orderId: response.data.data
              }
            })
          } else {
            this.$toast.fail('下单失败');
          }
        })
      }
      return !shouldRedirect;
    },
    //点击复制
    ctrlC(e) {
      let value = this.order.orderId
      handleCopy(value, e, () => {
        this.$toast('复制成功')
      }, () => {
        this.$toast('复制失败')
      })
    },
    findByMileageFee() {
      axios.get('http://localhost:8081/passenger/order/findByMileageFee').then(res => {
        console.log(res.data.data)
        this.mileageFee = res.data.data.mileageFee
        // 起步价
        this.startFee = res.data.data.startingPrice
        // 起步公里
        this.startingKilometer = res.data.data.startingKilometer
        console.log("里程费：", this.mileageFee)
        console.log("起步价：", this.startFee)
        console.log("起步公里：", this.startingKilometer)
      })
    },
    toHomeIndex() {
      this.$router.push({
        path: '/',
        query: {
          startaddress: this.startaddress,
          endaddress: this.endaddress
        }
      })
    },
    startAndEnd() {
      this.startLatitudeAndLongitude = this.$route.query.startLatitudeAndLongitude;
      this.endLatitudeAndLongitude = this.$route.query.endLatitudeAndLongitude;
      console.log("666", this.startaddress)
      console.log("777", this.endaddress)
    },

    findByCartTypeList() {
      axios.post('http://localhost:8081/passenger/cart/findByCartTypeList', this.cartType).then(response => {
        this.cartTypeList = response.data.data
      })
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "9708bfa416d306b9dbaf55ea4e4a25f2",
      };
      let self = this;
      AMapLoader.load({
        key: "e6effe38515227141202b9fb6749424e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      }).then((AMap) => {
        var map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          center: [116.397428, 39.90923],//地图显示中心点坐标
        });
        // 逆地址
        var geocoder = new AMap.Geocoder({
          city: "", //城市设为北京，默认：“全国”
        });
        AMap.plugin(
            ["AMap.ToolBar", "AMap.Driving", "AMap.Polyline", "AMap.Marker"],
            function () {
              //异步同时加载多个插件
              var toolbar = new AMap.ToolBar();
              map.addControl(toolbar);
              var driving = new AMap.Driving({
                map: map,
              }); //驾车路线规划
              // var在函数作用外,否则无法调用
              var startTranse = self.startLatitudeAndLongitude.split(",");
              var endTranse = self.endLatitudeAndLongitude.split(",");
              driving.search(
                  // 因地址值用2214.111的经纬度,所以需要格式转换
                  new AMap.LngLat(parseFloat(startTranse[0]), parseFloat(startTranse[1])),
                  new AMap.LngLat(parseFloat(endTranse[0]), parseFloat(endTranse[1])),
                  function (status, result) {
                    if (status === "complete") {
                      console.log("绘制驾车路线完成", result);
                      // 在这一块需要设置加时时间和大概的路程多少公里,用四舍五入的方式计算
                      self.driverTime = Math.round(result.routes[0].time / 60);
                      self.driverLong = Math.round(result.routes[0].distance / 1000);

                      console.log("时间：", self.driverTime)
                      console.log("距离：", self.driverLong)

                      // 逆地理编码获取地址信息
                      var start = self.startLatitudeAndLongitude.split(",");
                      var end = self.endLatitudeAndLongitude.split(",");
                      // 寻找开始地址的方法
                      geocoder.getAddress(start, function (status, result) {
                        if (status === 'complete' && result.regeocode) {
                          self.startaddress = result.regeocode.formattedAddress;
                          console.log("111", self.startaddress)
                        } else {
                          console.log("获取开始地址失败");
                        }
                      });
                      // 寻找结束地址的方法
                      geocoder.getAddress(end, function (status, result) {
                        if (status === 'complete' && result.regeocode) {
                          self.endaddress = result.regeocode.formattedAddress;
                          console.log(result.regeocode + "end");
                          console.log("222", self.endaddress)
                        } else {
                          console.log("获取结束地址失败");
                        }
                      });
                      console.log(start, end)
                      var text = new AMap.Text({
                        position: new AMap.LngLat(end[0], end[1]),
                        text: '距离为' + self.driverLong + '公里 大约' + self.driverTime + '分钟',
                        offset: new AMap.Pixel(-20, -20)
                      })
                      console.log("里程：", self.driverLong)
                      console.log("分钟：", self.driverTime)
                      console.log("单价", self.mileageFee)
                      self.estimatedPrice = Math.round(((self.driverLong - self.startingKilometer) * self.mileageFee + self.startFee)*100)/100;
                      self.estimatedPrice1 = self.estimatedPrice - 5;
                      self.estimatedPrice2 = self.estimatedPrice - 10;
                      self.estimatedPrice3 = self.estimatedPrice - 15;
                      console.log("estimatedPrice", self.estimatedPrice)

                      map.add(text);
                    } else {
                      console.log("获取驾车数据失败：" + result);
                    }
                  }
              );
            }
        );
      })
    },


  }
}
</script>


<style scoped>
.cart {
  width: 100%;
  height: 100vh;

  .popup {
    .first {
      width: 100%;
      height: 90%;
      margin-top: 40px;
      margin-left: 30px;

      .t {
        font-weight: bold;
        font-size: 20px;
        margin-bottom: 10px;
      }

      .order {
        width: 380px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .icon {
        float: left;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        overflow: hidden;
        margin-top: 20px;
        margin-right: 10px;
      }

      .money {
        width: 90%;
        height: 30%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 60px;
        color: red;
      }
    }
  }

  #container {
    width: 100%;
    height: 70vh;
  }

  .HomeIndex {
    width: 50px;
    height: 50px;
    position: fixed;
    top: 70vh;
    margin-left: 10px;
    margin-top: -62px;
    float: left;
  }

  .cart-name {
    float: left;
    margin-left: 28px;
    margin-top: -24px;
  }

  .price {
    width: 92px;
    height: 40px;
    float: left;
    margin-top: -3px;
    margin-left: 20px;
    font-size: 15px;
    //background-color: #f6e992;
  }

  .price1 {
    width: 92px;
    height: 40px;
    float: left;
    margin-top: 15px;
    margin-left: 21px;
    font-size: 15px;
    //background-color: #ef005c;
  }

  .price2 {
    width: 92px;
    height: 40px;
    float: left;
    margin-top: 26px;
    margin-left: 21px;
    font-size: 15px;
    //background-color: #f692e2;
  }

  .price3 {
    width: 110px;
    height: 40px;
    float: left;
    margin-top: -23px;
    margin-left: 21px;
    font-size: 15px;
    //background-color: #a892f6;
  }

  .estimatedPrice2 {
    width: 110px;
    height: 40px;
    float: left;
    margin-top: -25px;
    margin-left: 21px;
    //background-color: #f692e2;
  }

  .estimatedPrice {
    width: 110px;
    height: 40px;
    float: left;
    margin-top: 4px;
    margin-left: 0px;
    //background-color: #42b983;
  }

  .estimatedPrice1 {
    width: 110px;
    height: 40px;
    float: left;
    line-height: inherit;
    margin-top: -8px;
    margin-left: 0px;
    //background-color: #42b983;
  }

  .estimatedPrice2 {
    width: 110px;
    height: 40px;
    float: left;
    line-height: inherit;
    margin-top: -27px;
    margin-left: 0px;
    //background-color: #42b983;
  }

  .cart-type {
    width: 50%;
    height: 176px;
    //background-color: #4B9EFF;
    margin-top: 10px;
    line-height: 50px;
    text-align: center;
    font-size: 14px;
  }

  .cart-time {
    width: 50%;
    height: 45px;
    margin-top: 0px;
    margin-left: 0px;
    //background-color: #3CD38F;
  }

  .radio {
    float: left;
    margin-left: 334px;
    margin-top: -172px;
    padding: 10px 0;
  }

  .radio2 {
    float: left;
    margin-left: 334px;
    margin-top: -133px;
    padding: 10px 0;
  }

  .radio3 {
    float: left;
    margin-left: 334px;
    margin-top: -87px;
    padding: 10px 0;
  }

  .radio4 {
    float: left;
    margin-left: 334px;
    margin-top: -40px;
    padding: 10px 0;
  }

  .clock {
    margin-left: 33px;
    margin-top: 10px;
    font-size: 20px;
  }

  .clock-text {
    margin-left: 4px;
    margin-top: 28px;
    font-size: 15px;
  }

  .cart-cart {
    width: 50%;
    height: 45px;
    margin-top: -44px;
    margin-left: 193px;
    //background-color: #ffa1d4;
  }

  .cart-type-price {
    width: 100%;
    height: 130px;
    background-color: #f6e992;
  }

  .priceCard {
    width: 100%;
    height: 176px;
    float: left;
    margin-top: -176px;
    margin-left: 187px;
    background-color: palevioletred;
  }
}


</style>